package db

import (
	"database/sql"
	"fmt"
	"strings"
	"sync"
	"time"
	"ug-uploads/config"
	"ug-uploads/logx"

	_ "github.com/mattn/go-sqlite3"
	"go.uber.org/zap"
)

var (
	SqliteDB   *sql.DB
	onceSqlite sync.Once
)

func Init() error {
	var initErr error
	onceSqlite.Do(func() {
		db, err := sql.Open("sqlite3", config.Cfg.DBPath)

		if err != nil {
			initErr = fmt.Errorf("打开sqlite文件失败: %v", err)
			return
		}

		db.SetMaxOpenConns(1)
		db.SetMaxIdleConns(1)
		db.SetConnMaxLifetime(time.Hour)

		schema := `
			CREATE TABLE IF NOT EXISTS uploads (
				id INTEGER PRIMARY KEY AUTOINCREMENT,
				uniId TEXT UNIQUE,
				status TEXT,
				uploaded_at DATETIME
			);
		`
		if _, err := db.Exec(schema); err != nil {
			initErr = fmt.Errorf("sqlite执行出错: %v", err)
			return
		}

		if err := db.Ping(); err != nil {
			initErr = fmt.Errorf("sqlite连接失败: %v", err)
			return
		}

		SqliteDB = db

		logx.Logger.Info("数据库系统初始化完成", zap.String("database", "sqlite"))

	})

	if initErr != nil {
		return initErr
	}

	return nil
}

func CloseSqlite() error {
	if SqliteDB != nil {
		if err := SqliteDB.Close(); err != nil {
			return err
		}
	}
	return nil
}

func AlreadyUploaded(id string) (bool, error) {
	var count int
	err := SqliteDB.QueryRow("SELECT COUNT(*) FROM uploads WHERE uniId = ?", id).Scan(&count)
	return count > 0, err
}

func MarkUploaded(id string) (sql.Result, error) {
	if strings.TrimSpace(id) == "" {
		return nil, fmt.Errorf("uniId为空白, 不做sqlite标记处理")
	}
	res, err := SqliteDB.Exec("INSERT OR REPLACE INTO uploads (uniId, status, uploaded_at) VALUES (?, ?, ?)", id, "done", time.Now())
	return res, err
}
